package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.mapper.SalesOrderItemMapper;
import com.yupi.springbootinit.model.entity.SalesOrderItem;
import com.yupi.springbootinit.service.SalesOrderItemService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 订单明细服务实现
 */
@Service
@Slf4j
public class SalesOrderItemServiceImpl extends ServiceImpl<SalesOrderItemMapper, SalesOrderItem>
        implements SalesOrderItemService {

    @Resource
    private SalesOrderItemMapper salesOrderItemMapper;

    @Override
    public List<SalesOrderItem> getByOrderId(Long orderId) {
        if (orderId == null) {
            return List.of();
        }
        return salesOrderItemMapper.selectByOrderId(orderId);
    }

    @Override
    public List<SalesOrderItem> getByOrderNumber(String orderNumber) {
        if (orderNumber == null || orderNumber.trim().isEmpty()) {
            return List.of();
        }
        return salesOrderItemMapper.selectByOrderNumber(orderNumber);
    }

    @Override
    public List<SalesOrderItem> getByOrderIds(List<Long> orderIds) {
        if (orderIds == null || orderIds.isEmpty()) {
            return List.of();
        }
        return salesOrderItemMapper.selectByOrderIds(orderIds);
    }

    @Override
    public boolean saveBatchItems(List<SalesOrderItem> items) {
        if (items == null || items.isEmpty()) {
            return true;
        }
        return this.saveBatch(items);
    }

    @Override
    public boolean deleteByOrderId(Long orderId) {
        if (orderId == null) {
            return false;
        }
        int count = salesOrderItemMapper.deleteByOrderId(orderId);
        return count > 0;
    }

    @Override
    public boolean updateOrderItems(Long orderId, String orderNumber, List<SalesOrderItem> items) {
        if (orderId == null) {
            return false;
        }

        // 先删除该订单的所有明细（软删除）
        deleteByOrderId(orderId);

        // 如果没有提供新的明细列表，直接返回成功
        if (items == null || items.isEmpty()) {
            return true;
        }

        // 设置订单ID和订单号，并设置排序顺序
        for (int i = 0; i < items.size(); i++) {
            SalesOrderItem item = items.get(i);
            item.setOrderId(orderId);
            item.setOrderNumber(orderNumber);
            item.setSortOrder(i);
            // 清空ID，确保是新增而不是更新
            item.setId(null);
        }

        // 批量保存新的明细
        return saveBatchItems(items);
    }
}